package com.sinogrand.elevator.repository

import android.content.Context
import android.util.Log
import com.sinogrand.elevator.data.models.LoginResponse
import com.google.gson.JsonObject
import com.sinogrand.elevator.network.NetworkClient
import com.sinogrand.elevator.utils.LogTags
import com.sinogrand.elevator.utils.TokenManager
import com.sinogrand.elevator.utils.AuthStateManager

/**
 * 登录仓库类
 */
class LoginRepository(private val context: Context) {
    
    private val apiService = NetworkClient.getApiService(context)
    private val tokenManager = TokenManager(context)
    
    /**
     * 执行登录
     */
    suspend fun login(mobile: Long, password: String): Result<LoginResponse> {
        return try {
            val request = JsonObject().apply {
                addProperty("mobile", mobile)
                addProperty("password", password)
            }
            val apiResponse = apiService.login(request)
            
            if (apiResponse.code == 0 && apiResponse.data != null) {
                // 登录成功，保存token和用户信息
                tokenManager.saveTokenAndUserInfo(apiResponse.data.access_token, apiResponse.data.user_info)
                Log.i(LogTags.API, "✅ 登录成功 - 用户: ${apiResponse.data.user_info.real_name ?: "未知"} (${apiResponse.data.user_info.mobile})")
                Result.success(apiResponse.data)
            } else {
                // 登录失败
                Log.e(LogTags.API, "❌ 登录失败 - code: ${apiResponse.code}, msg: ${apiResponse.msg}")
                Result.failure(Exception(apiResponse.msg))
            }
        } catch (e: Exception) {
            Log.e(LogTags.API, "💥 登录异常 - ${e.javaClass.simpleName}: ${e.message}")
            Result.failure(e)
        }
    }
    
    /**
     * 检查是否已登录
     */
    fun isLoggedIn(): Boolean {
        return tokenManager.isLoggedIn()
    }
    
    /**
     * 退出登录
     */
    fun logout() {
        AuthStateManager.logout()
    }
}
